/**
 * 轮播图相关的自定义Hook
 *
 * 使用React Query进行数据获取和缓存管理
 * React Query提供了强大的数据同步、缓存和错误处理功能
 */
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { bannerService, BannerListParams } from '../services/bannerService';
import { Banner, BannerCreate, BannerUpdate } from '../types';

// 查询键常量
const QUERY_KEYS = {
  banners: ['banners'] as const,
  banner: (id: number) => ['banners', id] as const,
  activeBanners: ['banners', 'active'] as const,
};

/**
 * 获取轮播图列表
 */
export const useBanners = (params: BannerListParams = {}) => {
  return useQuery({
    queryKey: [...QUERY_KEYS.banners, params],
    queryFn: () => bannerService.getBanners(params),
    staleTime: 5 * 60 * 1000, // 5分钟内数据被认为是新鲜的
    gcTime: 10 * 60 * 1000, // 10分钟后清除缓存
  });
};

/**
 * 获取单个轮播图详情
 */
export const useBanner = (id: number) => {
  return useQuery({
    queryKey: QUERY_KEYS.banner(id),
    queryFn: () => bannerService.getBanner(id),
    enabled: !!id, // 只有当id存在时才执行查询
  });
};

/**
 * 获取激活的轮播图（用于前台显示）
 */
export const useActiveBanners = () => {
  return useQuery({
    queryKey: QUERY_KEYS.activeBanners,
    queryFn: () => bannerService.getActiveBanners(),
    staleTime: 10 * 60 * 1000, // 10分钟内数据被认为是新鲜的
  });
};

/**
 * 创建轮播图
 */
export const useCreateBanner = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (data: BannerCreate) => bannerService.createBanner(data),
    onSuccess: () => {
      // 创建成功后，使相关查询失效，触发重新获取
      queryClient.invalidateQueries({ queryKey: QUERY_KEYS.banners });
      queryClient.invalidateQueries({ queryKey: QUERY_KEYS.activeBanners });
    },
  });
};

/**
 * 更新轮播图
 */
export const useUpdateBanner = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({ id, data }: { id: number; data: BannerUpdate }) =>
      bannerService.updateBanner(id, data),
    onSuccess: (updatedBanner) => {
      // 更新成功后，更新缓存中的数据
      queryClient.setQueryData(
        QUERY_KEYS.banner(updatedBanner.id),
        updatedBanner
      );

      // 使列表查询失效
      queryClient.invalidateQueries({ queryKey: QUERY_KEYS.banners });
      queryClient.invalidateQueries({ queryKey: QUERY_KEYS.activeBanners });
    },
  });
};

/**
 * 删除轮播图
 */
export const useDeleteBanner = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (id: number) => bannerService.deleteBanner(id),
    onSuccess: (_, deletedId) => {
      // 删除成功后，从缓存中移除数据
      queryClient.removeQueries({ queryKey: QUERY_KEYS.banner(deletedId) });

      // 使列表查询失效
      queryClient.invalidateQueries({ queryKey: QUERY_KEYS.banners });
      queryClient.invalidateQueries({ queryKey: QUERY_KEYS.activeBanners });
    },
  });
};

/**
 * 轮播图管理的综合Hook
 * 提供了完整的CRUD操作
 */
export const useBannerManagement = () => {
  const createMutation = useCreateBanner();
  const updateMutation = useUpdateBanner();
  const deleteMutation = useDeleteBanner();

  return {
    // 创建
    createBanner: createMutation.mutate,
    isCreating: createMutation.isPending,
    createError: createMutation.error,

    // 更新
    updateBanner: updateMutation.mutate,
    isUpdating: updateMutation.isPending,
    updateError: updateMutation.error,

    // 删除
    deleteBanner: deleteMutation.mutate,
    isDeleting: deleteMutation.isPending,
    deleteError: deleteMutation.error,

    // 重置错误状态
    resetErrors: () => {
      createMutation.reset();
      updateMutation.reset();
      deleteMutation.reset();
    },
  };
};